package com.toivan.mt.adapter;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hwangjr.rxbus.RxBus;
import com.toivan.mt.R;
import com.toivan.mt.model.MtSharedPrefKey;
import com.toivan.mt.model.MtWatermark;
import com.toivan.mt.model.RxBusAction;
import com.toivan.mt.utils.MtSharedPreferences;
import com.toivan.sdk.MtSDK;

import java.util.List;

public class MtWatermarkAdapter extends RecyclerView.Adapter<MtStickerViewHolder> {

    private int selectedPosition = MtSharedPreferences.getInstance().getWatermarkPosition();

    private final List<MtWatermark> list;

    public MtWatermarkAdapter(List<MtWatermark> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public MtStickerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mt_sticker, parent, false);
        return new MtStickerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final MtStickerViewHolder holder, int position) {
        final MtWatermark watermark = list.get(holder.getAdapterPosition());

        if (selectedPosition == position) {
            holder.itemView.setSelected(true);
        } else {
            holder.itemView.setSelected(false);
        }

        holder.downloadIV.setVisibility(View.GONE);
        holder.thumbIV.setImageDrawable(list.get(position).getThumbDrawable(holder.itemView.getContext()));

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MtSDK.get().setWatermark(watermark.getName(), watermark.getX(), watermark.getY(), watermark.getRatio());
                MtSharedPreferences.getInstance().setWatermarkName(watermark.toString(), holder.getAdapterPosition());

                //切换选中背景
                int lastPosition = selectedPosition;
                selectedPosition = holder.getAdapterPosition();
                notifyItemChanged(selectedPosition);
                notifyItemChanged(lastPosition);

                RxBus.get().post(RxBusAction.ACTION_ENABLE_CANCEL, "");
            }
        });
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public void cancelSelected() {
        selectedPosition = -1;

        MtSDK.get().setWatermark("", 0, 0, 0);
        MtSharedPreferences.getInstance().setWatermarkName("", selectedPosition);

        notifyDataSetChanged();
    }


}


